// services/api/auth.ts
import { http } from '@/lib/request'
import { useAuthStore, type User } from '@/stores/auth'

interface LoginParams {
  username: string
  password: string
}

interface LoginResponse {
  token: string
  user: User
}

export const authService = {
  // 登录
  login: async (params: LoginParams) => {
    const response = await http.post<LoginResponse>('/wechat/loginByemail', {
      email: params.username,
      password: params.password,
    })
    // 保存认证信息
    useAuthStore.getState().setAuth(response.token, response.user)
    return response
  },

  // 登出
  logout: async () => {
    try {
      await http.post('/api/auth/logout')
    } finally {
      // 无论请求是否成功，都清除本地认证信息
      useAuthStore.getState().clearAuth()
    }
  },

  // TODO: 获取用户权限
  getAuthList: async () => {
    /*
  "id": 1,
  "name": "视频创作-换脸",
  "sign": "videoCreation_swapFace",
  "created_at": "2024-12-26 14:09:06",
  "updated_at": "2024-12-26 14:09:06",
  "permissionService": {
  "userHasPermissionModel": null,
  "type": "permission",
  "default_permission": {
  "name": "permission",
  "default_value": 0
  },
  "has_view": false,
  "has_edit": false,
  "has_admin": false
  }*/
    const response = await http.get<any>('/permission/list')
    // 保存认证信息
    const authList: {
      has_admin: boolean
      has_edit: boolean
      has_view: boolean // 是否有 上传面部图像
      sign: string
      name: string
    }[] = response.map((item: any) => {
      return {
        has_admin: item?.permissionService?.has_admin,
        has_edit: item?.permissionService?.has_edit,
        has_view: item?.permissionService?.has_view,
        sign: '',
        name: '',
      }
    })
    useAuthStore.getState().setAuthList(authList)
    return response
  },

  // 获取当前用户信息
  getCurrentUser: async (): Promise<User> => {
    const response = await http.get<{
      user: User
    }>('/auth/me')
    const userInfo = response?.user
    if (!userInfo) {
      throw new Error('用户信息不存在')
    }

    return {
      id: response.user.id,
      wecom_id: response.user.wecom_id,
      name: response.user.name,
      nickname: response.user.nickname,
      avatar: response.user.avatar,
      email: response.user.email,
    }
  },
}
